package com.ourcraft.informationcollectionsystem.controller.province;

import com.alibaba.fastjson.JSONObject;
import com.ourcraft.informationcollectionsystem.entity.Role;
import com.ourcraft.informationcollectionsystem.service.common.CommonService;
import com.ourcraft.informationcollectionsystem.service.province.roleManage.RoleManageService;
import com.ourcraft.informationcollectionsystem.utils.authority.AuthorityCode;
import com.ourcraft.informationcollectionsystem.utils.authority.AuthorityValidator;
import com.ourcraft.informationcollectionsystem.utils.response.Result;
import com.ourcraft.informationcollectionsystem.utils.response.ResultCode;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 处理角色管理模块相关的请求
 *
 * @author Z0136
 * @since 2023-11-4
 */
@RequestMapping("province/roleManage/")
@RestController
@CrossOrigin()
@AuthorityValidator(code = AuthorityCode.ROLE_MANAGE) // 按照‘角色管理’权限对接口访问进行限制
public class RoleManageController {
    @Autowired
    private RoleManageService roleManageService;
    @Autowired
    private CommonService commonService;

    /**
     * 处理‘province/roleManage/allRoles’接口的前端请求，获取所有角色信息
     *
     * @param request 用于权限验证
     * @return 所有角色的Id、权限、描述、名称信息
     */
    @GetMapping("allRoles")
    public Result<List<Role>> getAllRoles(HttpServletRequest request) {
        return Result.success(commonService.getAllRoles());
    }

    /**
     * 处理‘province/roleManage/deleteRole’接口的前端请求，删除角色
     *
     * @param roleId  删除角色的Id
     * @param request 用于权限验证
     * @return 是否删除成功
     */
    @DeleteMapping("deleteRole")
    public Result<Boolean> deleteRole(@RequestParam Integer roleId, HttpServletRequest request) {
        boolean success = roleManageService.deleteRole(roleId);
        if (success) return Result.success();
        return Result.fail(ResultCode.FAIL, "存在该角色的用户，无法删除角色");
    }

    /**
     * 处理‘province/roleManage/createRole’接口的前端请求，创建新角色
     *
     * @param role    包含创建角色的Id、权限、描述、名称信息
     * @param request 用于权限验证
     * @return 是否创建成功
     */
    @PostMapping("createRole")
    public Result<Boolean> createRole(@RequestBody Role role, HttpServletRequest request) {
        boolean success = roleManageService.createRole(role);
        if (success) return Result.success();
        return Result.fail();
    }

    /**
     * 处理‘province/roleManage/modifyRole’接口的前端请求，修改角色信息
     *
     * @param role    包含修改角色的Id，修改后权限、描述、名称
     * @param request 用于权限验证
     * @return 是否修改成功
     */
    @PutMapping("modifyRole")
    public Result<Boolean> modifyRole(@RequestBody Role role, HttpServletRequest request) {
        boolean success = roleManageService.modifyRole(role);
        if (success) return Result.success();
        return Result.fail();
    }
}
